<?

//process a Geograph website login

include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

init_session();

require_once($_SERVER['DOCUMENT_ROOT'].'/geograph/download/token.class.php');

$token=new Token;
$token->magic = $CONF['geograph_magic'];

if (isset($_GET['t']) && $token->parse($_GET['t']) && $token->hasValue('k') && $token->getValue('k') == $CONF['geograph_apikey']) {
    if ($token->hasValue('user_id') && $token->getValue('user_id') != '' ) {
	#if you get back a user_id you can be certain that they logged in on that account
	
	$geo_bi_id=$token->getValue('user_id');
	$realname=$token->getValue('realname');
	
	
	$user = getRow("SELECT * FROM `user` WHERE geo_bi_id = ".intval($geo_bi_id));
	
	if (empty($user)) {
		//not been here before... 
		$updates = array();

		$updates['geo_bi_id'] = $geo_bi_id;
		$updates['realname'] = $realname;
		$updates['created'] = 'NOW()';

		$sql= updates_to_insert('user',$updates);
		queryExecute($sql);
		
		$user_id = mysql_insert_id();
		
		//log the user
		$u = array();
		$u['table'] = 'user';
		$u['table_id'] = $user_id;
		$u['name'] = 'realname';
		$u['value'] = $realname;
		$u['user_id'] = $user_id;
		$sql= updates_to_insert('update_log',$u);
		queryExecute($sql);
		
	} elseif ($realname != $user['realname']) {
		//they changed their name!
		
		$user_id = $user['user_id'];
		$updates = array();
		$updates['realname'] = $realname;
		$updates['last_login'] = 'NOW()';
		
		$sql= updates_to_update('user',$updates,'user_id',$user_id);
		queryExecute($sql);
		
		//log the user
		$u = array();
		$u['table'] = 'user';
		$u['table_id'] = $user_id;
		$u['name'] = 'realname';
		$u['value'] = $realname;
		$u['user_id'] = $user_id;
		$sql= updates_to_insert('update_log',$u);
		queryExecute($sql);

	} else {
		$user_id = $user['user_id'];
		$updates = array();
		$updates['last_login'] = 'NOW()';

		$sql= updates_to_update('user',$updates,'user_id',$user_id);
		queryExecute($sql);
	}
	
	$_SESSION['user_id'] = $user_id;
	$_SESSION['realname'] = $realname;
	
	header("HTTP/1.0 303 See Other");
	header("Status: 303 See Other");
	
	if (empty($_SESSION['continue'])) {
		header("Location: ./");
	} else {
		header("Location: ".$_SESSION['continue']);
	}
	
	print "<a href=./>continue...</a>";
	
    } else {
	die("login failed");
    }
} else {
    die("invalid callback");
}
